package com.winai.launcher.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.bean.db.CurrentLocation;
import com.winai.launcher.bean.responseEntity.MojiEntity;
import com.winai.launcher.manager.WeatherManager;
import com.winai.launcher.view.LogicActivity;

import org.litepal.LitePal;

/**
 * @author kangshao
 * @date 2021/2/5
 * @desc 轮播图的天气服务
 */
public class WeatherService extends Service {
    private final IBinder binder = new MyBinder();
    private boolean weatherLoaded;
    private int count;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    /**
     * 说明：获取天气信息
     */
    public synchronized void banner_getWeather(Context mContext) {
        while (!weatherLoaded && count < 5) {
            try {
                count++;
                LogUtils.d("第" + count + "次获取天气");
                WeatherManager.getInstance(mContext).requestWeatherData();
                Thread.sleep(3000);
                weatherLoaded = weatherLoaded(mContext);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (count >= 5 && !weatherLoaded) {
            hidingWeatherProgressBar(mContext);
            CurrentLocation last = LitePal.findLast(CurrentLocation.class);
            String adminArea = last.getAdminArea().replace("市", "");
            String locality = last.getLocality().contains("市") ? last.getLocality() : last.getLocality() + "市";
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mContext, "天气获取失败:" + adminArea + "," + locality, Toast.LENGTH_SHORT).show();
                }
            });
            // 广播通知更新天气UI
            Intent intent = new Intent();
            intent.setAction(LogicActivity.ACTION_WEATHER_NULL);
            intent.putExtra("weatherNull", true);
            mContext.sendBroadcast(intent);
        }
    }

    private boolean weatherLoaded(Context mContext) {
        CurrentLocation last = LitePal.findLast(CurrentLocation.class);
        //更新天气信息
        MojiEntity mojiEntity = WeatherManager.getInstance(mContext).getMojiEntity();
        if (last != null && mojiEntity != null) {
            LogUtils.e("weatherDuiBean.getCityName()： " + mojiEntity.getCity()
                    + "，last.getLocality()：" + last.getLocality());
            if (mojiEntity.getCity().contains(last.getLocality())) {
                banner_updateViewData(mContext, mojiEntity);
            } else {
                //非本地位置，不更新
                LogUtils.e("非当前定位的位置，轮播图界面不更新天气数据");
            }
            return true;
        } else {
            showWeatherProgressBar(mContext);
            return false;
        }
    }

    private void banner_updateViewData(Context mContext, MojiEntity mojiEntity) {
        // 广播通知更新天气图标和温度
        Intent intent = new Intent();
        intent.setAction(LogicActivity.ACTION_UPDATE_WEATHER);
        intent.putExtra("mojiEntity", mojiEntity);
        mContext.sendBroadcast(intent);
    }

    private void showWeatherProgressBar(Context mContext) {
        // 广播通知
        Intent intent = new Intent();
        intent.setAction(LogicActivity.ACTION_SHOW_WEATHER_PROGRESS);
        intent.putExtra("showWeatherProgressBar", true);
        mContext.sendBroadcast(intent);
    }

    private void hidingWeatherProgressBar(Context mContext) {
        // 广播通知
        Intent intent = new Intent();
        intent.setAction(LogicActivity.ACTION_SHOW_WEATHER_PROGRESS);
        intent.putExtra("showWeatherProgressBar", false);
        mContext.sendBroadcast(intent);
    }

    /**
     * 该类是获得Service对象
     */
    public class MyBinder extends Binder {
        public WeatherService getService() {
            return WeatherService.this;
        }
    }

    @Override
    public void onCreate() {
        LogUtils.i("onCreate............");
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        LogUtils.i("onStart............");
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.i("onStartCommand............");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        LogUtils.i("onDestory............");
        super.onDestroy();
    }

}
